from websocket import create_connection
import gzip
import time
import json


def wbs():
    while True:
        try:
            ws = create_connection("wss://api.huobi.pro/ws")
            break
        except:
            print("connect ws error,retry...")
            time.sleep(5)
    # 订阅 Kline 消息
    tradeStr = """{"sub":"market.btcusdt.kline.1min", "id":"id1"}"""
    ws.send(tradeStr)
    while True:
        compressDate = ws.recv()
        result = gzip.decompress(compressDate).decode('utf-8')
        if result[:7] == '{"ping"':
            ts = result[8:21]
            pong = '{"pong":' + ts + '}'
            ws.send(pong)
            ws.send(tradeStr)
        else:
            print('============================')
            parse(result)


# 解析数据
def parse(result):
    results = json.loads(result)
    if results.get('tick'):
        data = results.get('tick')
        # 时间
        id = data['id']
        print(id)
        # 时间id转化为时间戳 因为 请求的分钟数据，所以不会展示秒
        time_local = time.localtime(int(id))
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        # 价格
        low = data['low']
        # 涨幅
        open = data['open']
        close = data['close']
        increase = '{:.2f} %'.format((close - open) / open * 100)
        # 需要的数据提取出来
        print(dt)
        print(low)
        print(increase)

# wbs()


